<template>
  <template v-if="loadChart">
    <RunningDuration :value="formInfo.totalDuration" classes="col q-mr-sm"
                     @click="getDurationMileage"></RunningDuration>
    <RunningMileage :value="formInfo.totalMileage" classes="col q-ml-sm" @click="getDurationMileage"></RunningMileage>
  </template>
  <q-modal v-model="modalVisible" v-model:loading="loading" :header="header" :menuBtn="false" :persistent="false"
           nonScrollArea width="800">
    <qx-table :data="tableData" :option="tableOption"></qx-table>
  </q-modal>
</template>
<script setup>
import { i18n } from 'boot/i18n.js'
import RunningDuration from 'pages/Dashboard/Console/RunningDuration.vue'
import RunningMileage from 'pages/Dashboard/Console/RunningMileage.vue'
import { postAPI } from 'src/api/index.js'
import { formatNumber } from 'src/utils/utils.js'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useTimeout } from 'quasar'

const action = ref('H')
const formInfo = ref({})
const tableData = ref([])
const loading = ref(false)
const loadChart = ref(false)
const modalVisible = ref(false)
const { registerTimeout, removeTimeout } = useTimeout()
const header = computed(
  () => action.value === 'H' ? i18n.t('Misc.ElapsedRunningDuration') : i18n.t('Misc.ElapsedRunningMileage'))
const tableOption = computed(() => {
  return {
    maxHeight: 'inherit',
    column: [{
      label: `${i18n.t('AGVCore.AGVCode')}`, field: 'agvBrandCode', minWidth: 60
    }, {
      label: `${i18n.t('AGVCore.AGVCode')}`, field: 'agvCode', minWidth: 60
    }, {
      label: `${i18n.t('Misc.ElapsedRunningDuration')}(H)`, field: 'agvRunTime',
      format: val => formatNumber(val / 1000 / 60 / 60, 2), hide: action.value !== 'H', minWidth: 60
    }, {
      label: `${i18n.t('Misc.ElapsedRunningMileage')}(KM)`, field: 'agvRunSum',
      format: val => formatNumber(val / 1000 / 1000, 2), hide: action.value !== 'KM', minWidth: 60
    }]
  }
})
const initData = () => {
  loadChart.value = true
  postAPI('/yfagv/api/agvAllStatus/selectSumData', {}, data => {
    const { sumAllDistance, sumAllDuration } = data
    formInfo.value.totalMileage = formatNumber(sumAllDistance / 1000 / 1000, 2)
    formInfo.value.totalDuration = formatNumber(sumAllDuration / 1000 / 60 / 60, 2)
  })
}
const getDurationMileage = source => {
  loading.value = true
  action.value = source
  const url = source === 'H' ? '/yfagv/api/agvAllStatus/selectAgvDate' : '/yfagv/api/agvAllStatus/selectAgvSum'
  postAPI(url, {}, data => {
    loading.value = false
    tableData.value = data
    modalVisible.value = true
  }, () => loading.value = false)
}

onMounted(() => registerTimeout(() => initData(), 10))
onUnmounted(() => removeTimeout && removeTimeout())
</script>